package com.cqc.jdk8.Jutil.concurrent.locks.ReadWriteLock;


import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Counter {
    private final int count = 0;
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    public void read() {
        lock.readLock().lock();
        try {
            System.out.println(DateFormat.getDateTimeInstance().format(new Date()) + "," + Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }

    public void write() {
        lock.writeLock().lock();
        try {
            System.out.println(DateFormat.getDateTimeInstance().format(new Date()) + "," + Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public int getCount() {
        return count;
    }
}
